package com.qf.chinatelcom.apiinterface.utils;


import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class IpUtils {
    public static String getRealIp(HttpServletRequest req) {
        String ip = null;
        //获取请求头中标记的真正的ip
        String xIp = req.getHeader("X-Real-IP");
        //我们可能会有多次的反向代理
        String xFor = req.getHeader("X-Forwarded-For");
        //这个 ip 不为空且不是 unknown
        if (!StringUtils.isEmpty(xFor) && !"unknow".equalsIgnoreCase(xFor)) {
            int index = xFor.indexOf(",");//获取第一个,的位置
            if (index > 0) {
                return xFor.substring(0, index);
            }
            return xFor;
        }

        ip = xIp;//有可能这个 ip 也没有

        //当前 ip 是空的
        if (StringUtils.isEmpty(ip) || "unknow".equalsIgnoreCase(ip)) {
            ip = req.getHeader("Proxy-Client-IP");
        }
        //上面获取的有可能还是空的
        if (StringUtils.isEmpty(ip) || "unknow".equalsIgnoreCase(ip)) {
            ip = req.getHeader("WL-Proxy-Client-IP");
        }

        if (StringUtils.isEmpty(ip) || "unknow".equalsIgnoreCase(ip)) {
            ip = req.getHeader("HTTP_CLIENT_IP");
        }

        if (StringUtils.isEmpty(ip) || "unknow".equalsIgnoreCase(ip)) {
            ip = req.getHeader("HTTP_X_FORWARDED_FOR");
        }

        if (StringUtils.isEmpty(ip) || "unknow".equalsIgnoreCase(ip)) {
            ip = req.getRemoteAddr();
        }

        return ip;

    }
}
